package com.student.demo.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author lsc
 * <p> JWT工具类 </p>
 * @Param
 * @Return
 */
public class JwtUtil {

    // Token过期时间30分钟
    public static final long EXPIRE_TIME = 30 * 60 * 1000;

    /**
     * @Author lsc
     * <p> 校验token是否正确 </p>
     * @Param token
     * @Param id
     * @Param secret
     * @Return boolean
     */
    public static boolean verify(String token, int id,String number,String role, String secret) {
        try {
            // 设置加密算法
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("id", id)
                    .withClaim("number",number)
                    .withClaim("role",role)
                    .build();
            // 效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }



    /**
     * @Author lsc
     * <p>生成签名,30min后过期 </p>
     * @Param [id, secret]
     * @Return java.lang.String
     */
    public static String sign(Integer id,String number,String role, String secret) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带id信息
        return JWT.create()
                .withClaim("id", id)
                .withClaim("number",number)
                .withClaim("role", role)
                .withExpiresAt(date)
                .sign(algorithm);

    }

    /**
     * @Author lsc
     * <p> 获取用户ID </p>
     * @Param [request]
     * @Return java.lang.String
     */
    public static int getIdByToken(HttpServletRequest request)  {
        String token = request.getHeader("token");
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("id")
                .asInt();
    }
    /**
     * token解析获取用户的number值
     * @author: 陈先生
     * @date 2021/4/29 14:45
     */
    public static String getNumberByToken(HttpServletRequest request)  {
        String token = request.getHeader("token");
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("number")
                .asString();
    }
    /**
     * token解析获取用户的role权限角色
     * @author: 陈先生
     * @date 2021/4/29 14:45
     */
    public static String getRoleByToken(HttpServletRequest request)  {
        String token = request.getHeader("token");
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("role")
                .asString();
    }


}


